package module.hostlink;

import common.BasicSerialPort;
import common.Const;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.FCS;
import util.HexFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TooManyListenersException;

/**
 * @author bingo
 * @Description
 * @Date 2018/8/22
 */
public class HostLink extends BasicSerialPort{

    private List<Integer> dataList ;

    private Logger logger = LoggerFactory.getLogger(HostLink.class);

    public  List<Integer> getDataList(){
       if(dataList==null){
           return  new ArrayList<>();
       }
       return  dataList;
    }



    public SerialPort open(CommPortIdentifier commPortIdentifier) {

        try {
            serialPort  = (SerialPort) commPortIdentifier.open(Object.class.getSimpleName(),2000);
            serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_7, SerialPort.STOPBITS_2, SerialPort.PARITY_EVEN);
            serialPort.addEventListener(new SerialPortListener());
            serialPort.notifyOnDataAvailable(true);
            serialPort.notifyOnBreakInterrupt(true);
        } catch (PortInUseException e) {
            logger.error("端口被占用");
            e.printStackTrace();
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
        }
        return serialPort;
    }
    @Override
    public String receive() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        StringBuffer stringBuffer=null;
        try {
              inputStream = serialPort.getInputStream();
             stringBuffer= new StringBuffer();
            int len =  inputStream.available();
            byte[] bys = new byte[len];
            while (len>0){
                 inputStream.read(bys);
                 len  = inputStream.read(bys);

            }
            stringBuffer.append(new String(bys));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                    logger.info("输入流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        analyzeData(stringBuffer.toString());
        logger.info("PLC返回数据:{}",stringBuffer.toString());
        HostLinkStartThread.isLock = false;
        return null;
    }

    private  void analyzeData(String s) {
        try {
            dataList  = new ArrayList<>();
            String methdCode = s.substring(3,5);
            if(methdCode.equalsIgnoreCase("RD")){
            int len = (s.length()-11)/4;
            logger.info("读取的数据个数:{}",len);
            for(int i=0;i<len;i++){
                int beginIndex = 7+i*4;
                String item = s.substring(beginIndex,beginIndex+4);
                dataList.add(Integer.parseInt(item,16));
                logger.info("item：{}",item);
            }
        }
     }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  @param addr PLC单元地址的BCD码
     *  @param  code 方法码
     *  @param startOffset 起始寻址地址
     *  @param value  值
     * */
    public void send(String addr,String code,String startOffset,short value[]){
        StringBuffer  dataBuffer =new StringBuffer();
        try {
            outputStream = serialPort.getOutputStream();
            dataBuffer.append(Const.HOSTlINK_PREFIX);
            dataBuffer.append(addr);
            dataBuffer.append(code);
            dataBuffer.append(startOffset);
            for(int i=0;i<value.length;i++){
                dataBuffer.append(HexFormat.formatHex(Integer.toHexString(value[i])));
            }
            dataBuffer.append(FCS.getFCS(dataBuffer.toString()));
            dataBuffer.append(Const.HOSTlINK_SUFFIX);
            byte[] bys = dataBuffer.toString().getBytes();
            outputStream.write(bys);
            logger.info("发送数据{}", dataBuffer.toString());
            }
            catch (IOException e) {
            e.printStackTrace();
        }finally {
             if(outputStream!=null){
                 try {
                     outputStream.close();
                     logger.info("输出流关闭");
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
        }

    }

    public void closePort(){
        logger.info("即将关闭串口");
        try{
            if(serialPort!=null){
                serialPort.close();
                logger.info("串口已经关闭");
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}



